<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Tree;
use app\admin\model\AuthDepartment;
use app\admin\model\AuthGroup;
use think\Config;
use app\admin\controller\general\Config as ConfigFile;

/**
 * 周销售统计
 *
 * @icon fa fa-circle-o
 */
class Sale extends Backend
{
    
    /**
     * Sale模型对象
     * @var \app\admin\model\Sale
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Sale;
        $this->view->assign("gradeList", $this->model->getGradeList());
        $this->view->assign("regionOrderList", $this->model->getRegionList());
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
        $position_data = array_column(collection(AuthGroup::field('id,name')->select())->toArray(), 'name','id');
        //职位信息
        unset($position_data[1]);//销毁管理员
        $this->view->assign('position_data',$position_data);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['lecturer'] = Admin::userName($value['lecturer']);
                $value['host'] = Admin::userName($value['host']);
                $value['finance'] = Admin::userName($value['finance']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 配置发送信息给某个 人 部门 标签，
     * @return string
     * @throws \think\Exception
     */
    public function config()
    {
        if($this->request->isPost())
        {
            $department = $this->request->request('department/a');
            $department = implode('|',$department);
            $tag = $this->request->request('group/a');
            $tag = implode('|',$tag);
            $userid = $this->request->request('user');
            $userid = implode('|',explode(',',$userid));
            $userids = $this->request->request('userids');
            $userids = implode('|',explode(',',$userids));
            $config = new \app\common\model\Config();
            $config->saleUpdate($userid,$tag,$department,$userids);//保存数据库  刷新配置文件
            ConfigFile::getRefreshFile();
            $this->success();
        }
        $array = [
            'userid'=>implode(',',explode('|',Config::get('site.userid'))),
            'tag'=>implode(',',explode('|',Config::get('site.tag'))),
            'department'=>implode(',',explode('|',Config::get('site.department'))),
            'userids'=>implode(',',explode('|',Config::get('site.userids'))),
        ];
        $this->view->assign("array", $array);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
